package com.zxl.template.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.kinggrid.iappoffice.IAppOffice;
import com.luliang.shapeutils.DevShapeUtils;
import com.luliang.shapeutils.shape.DevShape;
import com.zxl.template.R;
import com.zxl.template.base.BaseFrag;
import com.zxl.template.base.IActivity;
import com.zxl.template.constant.constant;
import com.zxl.template.http.JsonCallback;
import com.zxl.template.model.ContactRows;
import com.zxl.template.model.DocFile;
import com.zxl.template.model.DocRows;
import com.zxl.template.model.LDYJ;
import com.zxl.template.model.MsgEvent;
import com.zxl.template.model.Receipt;
import com.zxl.template.view.pop.FlowPop;
import com.zxl.template.view.pop.OpinionPop;
import com.zxl.zlibrary.http.OkHttpUtils;
import com.zxl.zlibrary.http.callback.FileCallBack;
import com.zxl.zlibrary.http.callback.StringCallback;
import com.zxl.zlibrary.tool.LEmptyTool;
import com.zxl.zlibrary.tool.LToast;
import com.zxl.zlibrary.tool.LogTool;
import com.zxl.zlibrary.view.statusview.LStatusView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * author : 王新海
 * time   : 2018/11/21.
 * version: 1.0.0
 * desc   : 收文详情
 */
public class DocDetailPager extends BaseFrag implements IActivity, constant {

    private static final String TAG = "DocDetailPager";
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_word)
    TextView tvWord;
    @BindView(R.id.tv_user)
    TextView tvUser;
    @BindView(R.id.tv_company)
    TextView tvCompany;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.et_opinion)
    EditText etOpinion;
    @BindView(R.id.checkbox)
    AppCompatCheckBox checkbox;
    @BindView(R.id.tv_way)
    TextView tvWay;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    @BindView(R.id.rv_text)
    RecyclerView rvText;
    @BindView(R.id.rv_file)
    RecyclerView rvFile;
    @BindView(R.id.tv_text)
    TextView tvText;
    @BindView(R.id.tv_file)
    TextView tvFile;
    @BindView(R.id.tv_dept_title)
    TextView tvDeptTitle;
    @BindView(R.id.tv_date_title)
    TextView tvDateTitle;
    @BindView(R.id.ll_layout)
    LinearLayout llLayout;
    @BindView(R.id.tv_iszwgk_title)
    TextView tvIszwgkTitle;
    @BindView(R.id.tv_iszwgk)
    TextView tvIszwgk;
    @BindView(R.id.tv_drawer_title)
    TextView tvDrawerTitle;
    @BindView(R.id.tv_drawer)
    TextView tvDrawer;
    @BindView(R.id.tv_main_unit_title)
    TextView tvMainUnitTitle;
    @BindView(R.id.tv_main_unit)
    TextView tvMainUnit;
    @BindView(R.id.iv_selected)
    ImageView ivSelected;
    @BindView(R.id.rl_tv_drawer)
    RelativeLayout rlTvDrawer;
    @BindView(R.id.rl_main_unit)
    RelativeLayout rlMainUnit;
    @BindView(R.id.tv_ldps_title)
    TextView tvLdpsTitle;
    @BindView(R.id.tv_ldps)
    TextView tvLdps;
    @BindView(R.id.rl_ldps)
    RelativeLayout rlLdps;
    @BindView(R.id.tv_nbyj_title)
    TextView tvNbyjTitle;
    @BindView(R.id.tv_nbyj)
    TextView tvNbyj;
    @BindView(R.id.rl_nbyj)
    RelativeLayout rlNbyj;
    @BindView(R.id.status_view)
    LStatusView statusView;
    @BindView(R.id.rv_ldyj)
    RecyclerView rvLdyj;

    private Unbinder unbinder;

    private List<DocFile> zwFileList = new ArrayList<>();
    private List<DocFile> fjFileList = new ArrayList<>();
    private RvFileAdapter rvFileAdapter;
    private RvTextAdapter rvTextAdapter;

    private SaveReceiver saveRec;
    private IAppOffice mAppOffice;
    private Receipt mReceipt;

    private boolean mReceiverFlag = false; //广播接受者标识

    private boolean officeFlag = false;

    private boolean isModify = false;//是否可以改稿
    private String toUserId;

    LocalBroadcastManager broadcastManager;

    private DocRows docRows;

    private List<Receipt.ChildFlows> childFlowsList = new ArrayList<>();
    private FlowPop flowPop;

    //改稿相关参数
    private File mFile;
    private DocFile mDocFile;
    private Context mContext;
    private boolean isSave = false;

    public static BaseFrag getInstance(DocRows docRows) {
        DocDetailPager receiptPager = new DocDetailPager();
        Bundle args = new Bundle();
        args.putSerializable("data", docRows);
        receiptPager.setArguments(args);
        return receiptPager;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.tab_receipt_pager, container, false);
        unbinder = ButterKnife.bind(this, inflate);

        broadcastManager = LocalBroadcastManager.getInstance(Objects.requireNonNull(getContext()));
        if (mContext == null)
            mContext = getContext();

        if (!mReceiverFlag) {
            //注册服务监听
            registerIntentFilters();
        }

        return inflate;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);


        initView();
        initData();
        initListener();
    }

    @Override
    public void initListener() {
        statusView.setOnViewRefreshListener(this::initNet);

        rvTextAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            DocFile item = (DocFile) adapter.getItem(position);
            assert item != null;
            ProgressDialog progressDialog = ProgressDialog.show(getContext(), "", "正在打开...", true);
            switch (view.getId()) {
                //改稿
                case R.id.tv_revise:
                    mApi.download(this, item.attachId, new FileCallBack(FILE_PATH, item.attachName.trim()) {
                        @Override
                        public void onError(Call call, Exception e, int i) {
                            LogTool.e(TAG, e);
                            LToast.error(e.getLocalizedMessage());
                            progressDialog.dismiss();
                        }

                        @Override
                        public void onResponse(File file, int i) {
                            progressDialog.dismiss();
                            if (mAppOffice != null) {
                                mAppOffice.unInit();
                            }

                            //需要初始化一次
                            mAppOffice = new IAppOffice(getActivity());
                            mAppOffice.setCopyRight(COPY_RIGHT);
                            mAppOffice.init();

                            if (mAppOffice.isWPSInstalled()) {
                                mFile = file;
                                mDocFile = item;
                                //打开WPS
                                mAppOffice.setFileName(file.getAbsolutePath());
                                mAppOffice.setUseMethod2(true);
                                mAppOffice.setIsReviseMode(true);
                                mAppOffice.setUserName(mApi.username);


                                mAppOffice.appOpen(true);
                            } else {
                                LToast.warning("请安装WPS专业版..");
                            }
                        }
                    });
                    break;
                //查看
                case R.id.tv_name:
                    //如果是gd 格式就调PDF
                    if (item.fileType.trim().toLowerCase().equals(".gd") || item.fileType.trim().toLowerCase().equals(".sep"))
                        mApi.downloadPdf(this, item.attachId, new FileCallBack(FILE_PATH, item.attachId + ".pdf") {
                            @Override
                            public void onError(Call call, Exception e, int i) {
                                LogTool.e(TAG, e);
                                LToast.error(e.getLocalizedMessage());
                                progressDialog.dismiss();
                            }

                            @Override
                            public void onResponse(File file, int i) {
                                progressDialog.dismiss();

                                if (mAppOffice.isWPSInstalled()) {
                                    //打开WPS
                                    mAppOffice.setFileName(file.getAbsolutePath());
                                    mAppOffice.setUseMethod2(true);
                                    //只读
                                    mAppOffice.setReadOnly(true);
                                    mAppOffice.appOpen(true);
                                } else {
                                    LToast.warning("请安装WPS专业版..");
                                }
                            }
                        });
                    else
                        mApi.download(this, item.attachId, new FileCallBack(FILE_PATH, item.attachName.trim()) {
                            @Override
                            public void onError(Call call, Exception e, int i) {
                                LogTool.e(TAG, e);
                                LToast.error(e.getLocalizedMessage());
                                progressDialog.dismiss();
                            }

                            @Override
                            public void onResponse(File file, int i) {
                                progressDialog.dismiss();
                                if (mAppOffice.isWPSInstalled()) {
                                    //打开WPS
                                    mAppOffice.setFileName(file.getAbsolutePath());
                                    mAppOffice.setUseMethod2(true);
                                    //只读
                                    mAppOffice.setReadOnly(true);
                                    mAppOffice.appOpen(true);
                                } else {
                                    LToast.warning("请安装WPS专业版..");
                                }
                            }
                        });
                    break;
            }
        });
        //改稿
        rvFileAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            DocFile item = (DocFile) adapter.getItem(position);
            assert item != null;
            ProgressDialog progressDialog = ProgressDialog.show(getContext(), "提示", "正在打开...", true);
            switch (view.getId()) {
                case R.id.tv_revise:
                    mApi.download(this, item.attachId, new FileCallBack(FILE_PATH, item.attachName.trim()) {
                        @Override
                        public void onError(Call call, Exception e, int i) {
                            LogTool.e(TAG, e);
                            LToast.error(e.getLocalizedMessage());
                            progressDialog.dismiss();
                        }

                        @Override
                        public void onResponse(File file, int i) {
                            progressDialog.dismiss();

                            if (mAppOffice != null) {
                                mAppOffice.unInit();
                            }
                            //需要初始化一次
                            mAppOffice = new IAppOffice(getActivity());
                            mAppOffice.setCopyRight(COPY_RIGHT);
                            mAppOffice.init();

                            if (mAppOffice.isWPSInstalled()) {
                                mFile = file;
                                mDocFile = item;

                                //打开WPS
                                mAppOffice.setFileName(file.getAbsolutePath());
                                mAppOffice.setUseMethod2(true);
                                mAppOffice.setIsReviseMode(true);
                                mAppOffice.setUserName(mApi.username);
                                mAppOffice.appOpen(true);
                            } else {
                                LToast.warning("请安装WPS专业版..");
                            }
                        }
                    });
                    break;

                //查看
                case R.id.tv_name:
                    //如果是gd 格式就调PDF
                    if (item.fileType.trim().toLowerCase().equals(".gd") || item.fileType.trim().toLowerCase().equals(".sep"))
                        mApi.downloadPdf(this, item.attachId, new FileCallBack(FILE_PATH, item.attachId + ".pdf") {
                            @Override
                            public void onError(Call call, Exception e, int i) {
                                LogTool.e(TAG, e);
                                LToast.error(e.getLocalizedMessage());
                                progressDialog.dismiss();
                            }

                            @Override
                            public void onResponse(File file, int i) {
                                progressDialog.dismiss();
                                if (mAppOffice.isWPSInstalled()) {
                                    //打开WPS
                                    mAppOffice.setFileName(file.getAbsolutePath());
                                    mAppOffice.setUseMethod2(true);
                                    //只读
                                    mAppOffice.setReadOnly(true);
                                    mAppOffice.appOpen(true);
                                } else {
                                    LToast.warning("请安装WPS专业版..");
                                }
                            }
                        });
                    else
                        mApi.download(this, item.attachId, new FileCallBack(FILE_PATH, item.attachName.trim()) {
                            @Override
                            public void onError(Call call, Exception e, int i) {
                                LogTool.e(TAG, e);
                                LToast.error(e.getLocalizedMessage());
                                progressDialog.dismiss();
                            }

                            @Override
                            public void onResponse(File file, int i) {
                                progressDialog.dismiss();
                                if (mAppOffice.isWPSInstalled()) {
                                    //打开WPS
                                    mAppOffice.setFileName(file.getAbsolutePath());
                                    mAppOffice.setUseMethod2(true);
                                    //只读
                                    mAppOffice.setReadOnly(true);
                                    mAppOffice.appOpen(true);
                                } else {
                                    LToast.warning("请安装WPS专业版..");
                                }
                            }
                        });
                    break;
            }
        });
    }


    @Override
    public void initView() {
        DevShapeUtils.shape(DevShape.RECTANGLE).solid(R.color.textGreen).into(tvWay);
        DevShapeUtils.shape(DevShape.RECTANGLE).solid(R.color.colorAccent).into(tvEnd);

        llLayout.setVisibility(View.GONE);

        //附件稿适配器
        rvFile.setLayoutManager(new LinearLayoutManager(getContext()));
        rvFileAdapter = new RvFileAdapter(fjFileList);
        rvFile.setAdapter(rvFileAdapter);

        rvFileAdapter.setOnItemClickListener((adapter, view, position) -> {

        });


        //正文稿适配器
        rvText.setLayoutManager(new LinearLayoutManager(getContext()));
        rvTextAdapter = new RvTextAdapter(zwFileList);
        rvText.setAdapter(rvTextAdapter);


    }

    @Override
    public void initData() {
        if (!officeFlag) {
            //初始化iAppOffice
            mAppOffice = new IAppOffice(getActivity());
            mAppOffice.setCopyRight(COPY_RIGHT);
            mAppOffice.init();
            officeFlag = true;
        }

        assert getArguments() != null;
        docRows = (DocRows) getArguments().getSerializable("data");

        //收文
        assert docRows != null;
        if (docRows.documentType == DOC_TYPE_RECEIPT) {
            tvDeptTitle.setText("来文单位");
            tvDateTitle.setText("来文时间");


        } else {
            tvDeptTitle.setText("拟文单位");
            tvDateTitle.setText("拟文时间");

            //发文办理中没有领导审批和拟办意见
            rlLdps.setVisibility(View.GONE);
            rlNbyj.setVisibility(View.GONE);
        }

        assert docRows != null;
        try {
            initNet();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initNet() {
        statusView.onLoadingView();
        mApi.receiptDetail(this, docRows.documentType, docRows.documentId, new JsonCallback<Receipt>() {

            @Override
            public void onError(Call call, Exception e, int i) {
                LogTool.e(TAG, e);
                if (LEmptyTool.isNotEmpty(statusView))
                    statusView.onErrorView();
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onResponse(Receipt receipt, int i) {
                mReceipt = receipt;
                if (LEmptyTool.isNotEmpty(receipt.childFlows)) {
                    childFlowsList.clear();
                    childFlowsList.addAll(receipt.childFlows);
                }

                tvTitle.setText(myTrim(mReceipt.title));
                tvWord.setText(myTrim(mReceipt.word));

                //收文
                if (docRows.documentType == 2) {
                    tvIszwgkTitle.setText("公开属性");
//                    0此件不公开 1此件公开发布 2此件依申请公开 3此件删减后公开
                    switch (receipt.iszwgk) {
                        case 0:
                            tvIszwgk.setText("此件不公开");
                            break;
                        case 1:
                            tvIszwgk.setText("此件公开发布");

                            break;
                        case 2:
                            tvIszwgk.setText("此件依申请公开");

                            break;
                        case 3:
                            tvIszwgk.setText("此件删减后公开");

                            break;
                    }
                    tvDrawerTitle.setText("拟稿人");
                    tvDrawer.setText(myTrim(receipt.drawer));

                    tvDeptTitle.setText("拟稿单位");
                    tvCompany.setText(myTrim(mReceipt.agency));

                    tvDateTitle.setText("制文时间".trim());
                    tvDate.setText(myTrim(mReceipt.createTime));

                    tvMainUnitTitle.setText("主送单位");
                    tvMainUnit.setText(myTrim(receipt.mainDeliveryUnit));


                } else {
                    tvIszwgkTitle.setText("是否办理时限");
                    if (receipt.isCompleteLimit == 1) {
                        tvIszwgk.setText("是");

                        tvDrawerTitle.setText("限时时间");
                        tvDrawerTitle.setTextColor(Color.parseColor("#E00013"));

                        tvDrawer.setTextColor(Color.parseColor("#E00013"));
                        tvDrawer.setText(receipt.completeLimitTime);

                    } else {
                        tvIszwgk.setText("否");
                        rlTvDrawer.setVisibility(View.GONE);
                    }

                    tvDeptTitle.setText("来文单位");
                    tvCompany.setText(myTrim(mReceipt.fromUnit));

                    tvDateTitle.setText("来文时间");
                    tvDate.setText(mReceipt.toDate);

                    if (LEmptyTool.isNotEmpty(receipt.ldyjs)) {
                        rvLdyj.setVisibility(View.VISIBLE);
                        rvLdyj.setLayoutManager(new LinearLayoutManager(getContext()));
                        rvLdyj.setAdapter(new RvLDYJAdapter(receipt.ldyjs));

                    }
                    tvNbyj.setText(receipt.nbyj);


                    rlMainUnit.setVisibility(View.GONE);

                }

                //判断是否改稿
                if (receipt.handle != null && receipt.handle.status == 0) {
                    llLayout.setVisibility(View.VISIBLE);

                    if (LEmptyTool.isNotEmpty(receipt.handle)) {
                        if (receipt.handle.flowType == 1) {
                            if (receipt.flowMain != null)
                                tvEnd.setText(myTrim(receipt.flowMain.doneBtn));
                        } else {
                            if (receipt.flowChild != null)
                                tvEnd.setText(myTrim(receipt.flowChild.doneBtn));
                        }
                    }
                    if (!receipt.handle.title.equals("传阅")) {
                        isModify = true;
                    }
                }

                if (LEmptyTool.isNotEmpty(mReceipt.zwDocFiles)) {
                    zwFileList.clear();
                    zwFileList.addAll(mReceipt.zwDocFiles);
                    rvTextAdapter.notifyDataSetChanged();
                } else {
                    tvText.setVisibility(View.GONE);
                    rvText.setVisibility(View.GONE);
                }

                if (LEmptyTool.isNotEmpty(mReceipt.fjDocFiles)) {
                    fjFileList.clear();
                    fjFileList.addAll(mReceipt.fjDocFiles);
                    rvFileAdapter.notifyDataSetChanged();
                } else {
                    tvFile.setVisibility(View.GONE);
                    rvFile.setVisibility(View.GONE);
                }

                statusView.onSuccessView();
            }
        });
    }

    private class RvLDYJAdapter extends BaseQuickAdapter<LDYJ, BaseViewHolder> {

        RvLDYJAdapter(@Nullable List<LDYJ> data) {
            super(R.layout.item_ldyj, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, LDYJ item) {
            helper.setText(R.id.tv_opinion, item.opinion);
        }
    }

    private String myTrim(String str) {
        String s = str.replaceAll("\\s*", "");
        System.out.println(s);
        return s;
    }

    @OnClick({R.id.iv_selected, R.id.tv_end, R.id.tv_way})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_selected:
                OpinionPop opinionPop = new OpinionPop(getContext(), mReceipt.opinions);
                opinionPop.showPopupWindow();
                opinionPop.setOnCheckListener(item -> {
                    etOpinion.setText(item);
                    opinionPop.dismiss();
                });
                break;

            case R.id.tv_end:
                if (LEmptyTool.isNotEmpty(mReceipt.handle)) {
                    //如果主流程就调一下接口
                    if (mReceipt.handle.isChild == 0) {
                        mApi.findNextMainFlowUsers(this, mReceipt.handle.handleId, new JsonCallback() {
                            @Override
                            public void onError(Call call, Exception e, int i) {
                                LogTool.e(TAG, e);
                            }

                            @Override
                            public void onResponse(Object o, int i) {

                            }
                        });
                    }
                    String opinion = etOpinion.getText().toString();
                    if (LEmptyTool.isEmpty(opinion)) {
                        LToast.warning("请输入意见.");
                        return;
                    }

                    ProgressDialog progressDialog = ProgressDialog.show(getContext(), "", "正在处理...", true);
                    //保存意见
                    mApi.saveOpinion(this, mReceipt.handle.handleId, toUserId, opinion, checkbox.isChecked(), new JsonCallback() {
                        @Override
                        public void onError(Call call, Exception e, int i) {
                            LToast.error(e.getLocalizedMessage());
                            LogTool.e(TAG, e);
                            progressDialog.dismiss();
                        }

                        @Override
                        public void onResponse(Object o, int i) {
                            progressDialog.dismiss();
                            LToast.success("处理成功.");
                            EventBus.getDefault().post(new MsgEvent<>("refresh_doc_list", ""));
                            Objects.requireNonNull(getActivity()).finish();
//                            EventBus.getDefault().post(new MsgEvent<>("refresh_doc_detail", ""));


                        }
                    });
                }

                break;

            //流程定义
            case R.id.tv_way:
                flowPop = new FlowPop(getActivity(), childFlowsList, mReceipt, docRows);
                flowPop.showPopupWindow();
                flowPop.setRefresh(() -> {
                    Objects.requireNonNull(getActivity()).finish();
                });
                break;
            default:
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MsgEvent<List<ContactRows>> event) {
        if (event.type.equals("contact_pop")) {
            List<ContactRows> contactRows = event.t;
            if (LEmptyTool.isNotEmpty(flowPop)) {
                flowPop.fresh(contactRows);
            }
        } else if (event.type.equals("other")) {
            isModify = false;
        }
    }


    //正文稿
    class RvTextAdapter extends BaseQuickAdapter<DocFile, BaseViewHolder> {

        RvTextAdapter(@Nullable List<DocFile> data) {
            super(R.layout.item_doc_file, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, DocFile item) {
            helper.setText(R.id.tv_name, item.attachOriginalName);

            helper.addOnClickListener(R.id.tv_revise);
            helper.addOnClickListener(R.id.tv_name);

            //发文才有改稿功能
            if (docRows.documentType == DOC_TYPE_DISPATCH) {
                if (isModify && (item.fileType.equals(".doc") || item.fileType.equals(".docx"))) {
                    helper.getView(R.id.tv_revise).setVisibility(View.VISIBLE);
                } else {
                    helper.getView(R.id.tv_revise).setVisibility(View.GONE);
                }
            } else {
                helper.getView(R.id.tv_revise).setVisibility(View.GONE);
            }

        }
    }

    class RvFileAdapter extends BaseQuickAdapter<DocFile, BaseViewHolder> {

        RvFileAdapter(@Nullable List<DocFile> data) {
            super(R.layout.item_doc_file, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, DocFile item) {
            helper.setText(R.id.tv_name, item.attachOriginalName);

            helper.addOnClickListener(R.id.tv_name);
            helper.addOnClickListener(R.id.tv_revise);

            //发文才有改稿功能
            if (docRows.documentType == DOC_TYPE_DISPATCH) {
                if (isModify) {
                    helper.getView(R.id.tv_revise).setVisibility(View.VISIBLE);
                } else {
                    helper.getView(R.id.tv_revise).setVisibility(View.GONE);
                }
            } else {
                helper.getView(R.id.tv_revise).setVisibility(View.GONE);
            }

        }
    }


    public void registerIntentFilters() {
        if (saveRec == null && !mReceiverFlag) {
            IntentFilter saveFilter = new IntentFilter();
            saveFilter.addAction(BROADCAST_FILE_SAVE);
            IntentFilter closeFilter = new IntentFilter();
            closeFilter.addAction(BROADCAST_FILE_CLOSE);
            IntentFilter saveAsFilter = new IntentFilter();
            saveAsFilter.addAction(BROADCAST_FILE_SAVEAS);

            saveRec = new SaveReceiver();
            mContext.registerReceiver(saveRec, saveFilter);
            mContext.registerReceiver(saveRec, closeFilter);
            mContext.registerReceiver(saveRec, saveAsFilter);

            mReceiverFlag = true;
        }
    }

    public class SaveReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (BROADCAST_FILE_SAVE.equals(intent.getAction())) {
                isSave = true;
                Log.e(TAG, BROADCAST_FILE_SAVE + " : file save");
            } else if (BROADCAST_FILE_CLOSE.equals(intent.getAction())) {
                Log.e(TAG, BROADCAST_FILE_CLOSE + " : file close");
                if (isSave && LEmptyTool.isNotEmpty(mFile) && LEmptyTool.isNotEmpty(mDocFile)) {
                    ProgressDialog progressDialog = ProgressDialog.show(getContext(), "", "正在上传...", true);

                    String url = mApi.API + "document/uploadWord?attach_id=" + mDocFile.attachId;

                    OkHttpUtils
                            .post()
                            .addHeader("username", mApi.username)
                            .addHeader("password", mApi.password)
                            .addHeader("Content-Type", "multipart/form-data")
                            .addFile("file", mDocFile.attachOriginalName, mFile)
                            .tag(this)
                            .url(url)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int i) {
                                    LToast.error(e.getMessage());
                                    LogTool.e(TAG, e);
                                    progressDialog.dismiss();
                                }

                                @Override
                                public void onResponse(String s, int i) {
                                    progressDialog.dismiss();
                                    LToast.success("改稿成功.");
                                }
                            });
                } else if (BROADCAST_FILE_SAVEAS.equals(intent.getAction())) {
                    isSave = true;
                }
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mAppOffice != null && officeFlag) {
            mAppOffice.unInit();
            officeFlag = false;
        }

        if (mReceiverFlag && saveRec != null) {
            mReceiverFlag = false;
            mContext.unregisterReceiver(saveRec);
        }

        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();

    }

}
